package com.huiyou.control;

import com.huiyou.base.AppBack;
import com.huiyou.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 文件上传
 * @author fishlord
 *
 */
@Controller
public class FileController {
	
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);
	
	/**
	 * 上传
	 * @return
	 */
    @RequestMapping("/file/upload")
    @ResponseBody
	public AppBack upload(@RequestParam("file") MultipartFile file){
		//TODO
    	String fileName = file.getOriginalFilename();
        logger.info(fileName+"_"+file.getOriginalFilename()+"_"+file.getContentType());
    	String ext = fileName.substring(fileName.indexOf("."),fileName.length());
    	Random random = new Random();
    	fileName = "" + random.nextInt(10000) + System.currentTimeMillis() + ext;
    	 try {
			 file.transferTo(new File(Config.FilePath+fileName));
             return new AppBack(Config.BaseUrl+"files/"+fileName);
		 }catch (IOException e) {
			 logger.error("文件保存失败",e);
             return new AppBack(-1,"文件保存失败");
		 }
	}
    
    /**
     * 批量上传
     * @return
     */
    @RequestMapping("/file/mulUpload")
    @ResponseBody
    public Map mulUpload(@RequestParam(value = "upfile", required = true) MultipartFile[] files){
    	List<String> list = new ArrayList<>();
		 for (MultipartFile file : files) {
			 String fileName = file.getOriginalFilename();
			 String ext = fileName.substring(fileName.indexOf("."),fileName.length());
			 Random random = new Random();
			 fileName = "" + random.nextInt(10000) + System.currentTimeMillis() + ext;
			 try {
				 file.transferTo(new File(Config.FilePath+fileName));
				 list.add("files/"+fileName);

			 }catch (IOException e) {
				 logger.error("文件保存失败",e);
                 Map map=new HashMap();
                 map.put("code",-1);
                 return map;
			 }
		}
        Map map=new HashMap();
        map.put("code",0);
        map.put("data",list);
    	return map;
    }
}
